package com.sojson.util.mq.rabbit;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.sojson.constant.Constant;
import com.sojson.util.text.Convert;

/**
 * 队列连接工具类
 * 
 * @author liu
 * @date 2021-07-11
 */
public class ChannelUtil {

    /** 代理服务器IP */
    private static final String HOST = Constant.PROPERTIES.getProperty("so.mq.rabbit.host");
    /** 代理服务器端口号(默认为5672) */
    private static final int PORT = Convert.toInt(Constant.PROPERTIES.getProperty("so.mq.rabbit.port"), 5672);
    /** 代理服务器帐号 */
    private static final String USERNAME =
        Convert.toStr(Constant.PROPERTIES.getProperty("so.mq.rabbit.username"), "root");
    /** 代理服务器密码 */
    private static final String PASSWORD =
        Convert.toStr(Constant.PROPERTIES.getProperty("so.mq.rabbit.password"), "123456");
    /** 连接断开后重新连接的间隔时间(默认10秒) */
    private static final int TIME_RE_LOAD =
        Convert.toInt(Constant.PROPERTIES.getProperty("so.mq.rabbit.timeReLoad"), 1000 * 10);

    /**
     * 连接描述
     * 
     * @param connDesc  客户端提供的连接名称(任意字符串)。将显示在管理界面，如果服务器支持
     * @return
     */
    public static Channel getChannelInstance(String connDesc) {
        try {
            // 获取连接工厂
            ConnectionFactory connectionFactory = getConnectionFactory();
            // 获取连接
            Connection connection = connectionFactory.newConnection(connDesc);
            // 通过连接去创建传输数据的通道
            return connection.createChannel();
        } catch (Exception e) {
            throw new RuntimeException("获取Channel连接失败");
        }
    }

    private static ConnectionFactory getConnectionFactory() {
        ConnectionFactory connectionFactory = new ConnectionFactory();

        // 配置连接信息
        // connectionFactory.setHost(HOST);
        // connectionFactory.setPort(PORT);
        // connectionFactory.setUsername(USERNAME);
        // connectionFactory.setPassword(PASSWORD);
        //
        connectionFactory.setHost("192.168.120.120");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("root");
        connectionFactory.setPassword("123456");

        // 网络异常自动连接恢复
        connectionFactory.setAutomaticRecoveryEnabled(true);
        // 每N秒尝试重试连接一次
        // connectionFactory.setNetworkRecoveryInterval(TIME_RE_LOAD);
        connectionFactory.setNetworkRecoveryInterval(1000 * 10);

        return connectionFactory;
    }

    /**
     * 关闭资源(一般消费者不关闭,一直监听队列消息并消费)
     * 
     * @param channel
     * @param connection
     * @throws Exception
     */
    public static void close(Channel channel, Connection connection) throws Exception {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }

    }

}